package com.mama100.rpc.mdp.service.finagle;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.mama100.common.finagle.util.FinagleRPC;
import com.mama100.common.finagle.util.RpcUtil;
import com.mama100.rpc.mdp.MdpInoutUtil;
import com.mama100.rpc.mdp.constant.ResponseCode;
import com.mama100.rpc.mdp.thrift.inout.BindCustBrandRequest;
import com.mama100.rpc.mdp.thrift.inout.GetCustBrandRequest;
import com.mama100.rpc.mdp.thrift.inout.GetCustBrandResponse;
import com.mama100.rpc.mdp.thrift.inout.TCustBrand;
import com.mama100.rpc.mdp.thrift.inout.UnBindCustBrandRequest;
import com.mama100.rpc.mdp.thrift.inout.common.BaseResponse;
import com.twitter.util.ExecutorServiceFuturePool;
import com.twitter.util.Function0;
import com.twitter.util.Future;

@FinagleRPC
@Service("custBrandService")
public class CustBrandService implements com.mama100.rpc.mdp.thrift.CustBrandService.ServiceIface {
	protected Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ExecutorServiceFuturePool futurePool;

	@Resource(name = "cpmsJdbcTemplate")
	JdbcTemplate jdbcTemplate;

	@Override
	public Future<BaseResponse> bind(BindCustBrandRequest req) {

		return futurePool.apply(new Function0<BaseResponse>() {
			@Override
			public BaseResponse apply() {
				BaseResponse resp = new BaseResponse();

				if (req.getBaseReq().getSeqNo() == null) {
					resp.setSeqNo(RpcUtil.genSeqNo());
				} else {
					resp.setSeqNo(req.getBaseReq().getSeqNo());
				}
				log.info("receive:" + req.toString());
				// dbservice save
				try {
					long customerId = req.getCustomerId();
					long brandId = req.getBrandId();
					String fromSystem = req.getFromSystem();
					String updateBy = req.getUpdateBy();
					Date updateTime = new Date();

					if (brandId == 101L) {
						// 如果绑定101 不处理
						// 无此品牌绑定
						resp.setRespCode(ResponseCode.INVALID_REQUEST.getCode());
						resp.setRespDesc("101只在夜间批量计算出,无法绑定!");
						log.info("return:" + resp.toString());
						return resp;

					} else if (brandId == 100L) {
						// 会员已绑定了1、2、3、5其中一个或者多个。如果再想绑定100。 则不处理 // 因为是新会员 所以
						// 这儿只要发现有值 就不处理
						Long count = jdbcTemplate.queryForObject("select count(1) from cpms_cust_brand where customer_id =  " + customerId,
								Long.class);
						if (count > 0) {
							// 不处理
							resp.setRespCode(ResponseCode.INVALID_REQUEST.getCode());
							resp.setRespDesc("已经绑定品牌,不处理");
							log.info("return:" + resp.toString());
							return resp;

						} else {
							// 插入
							jdbcTemplate
									.update("insert into cpms_cust_brand (id,customer_id,brand_id,create_time,create_by,update_time,update_by,from_system) values ( CPMS_CUST_BRAND_SEQ.nextval,?,?,?,?,?,?,?  )",
											customerId, brandId, updateTime, updateBy, updateTime, updateBy, fromSystem);
						}
					} else if (brandId == 1 || brandId == 2 || brandId == 3 || brandId == 5) {
						// 如果会员绑定1,2,3,5,删除100,101
						jdbcTemplate.update("delete from cpms_cust_brand where customer_id=? and (brand_id = 100 or brand_id = 101) ", customerId);

						// update
						int updated = jdbcTemplate.update(
								"update  cpms_cust_brand set  update_by =  ? , update_time=?,from_system=? where customer_id =? and brand_id = ? ",
								updateBy, updateTime, fromSystem, customerId, brandId);
						if (updated == 0) {
							// insert
							jdbcTemplate
									.update("insert into cpms_cust_brand (id,customer_id,brand_id,create_time,create_by,update_time,update_by,from_system) values ( CPMS_CUST_BRAND_SEQ.nextval,?,?,?,?,?,?,?  )",
											customerId, brandId, updateTime, updateBy, updateTime, updateBy, fromSystem);

						}

					} else {
						// 无此品牌绑定
						resp.setRespCode(ResponseCode.INVALID_REQUEST.getCode());
						resp.setRespDesc("无此品牌绑定:" + brandId);
						log.info("return:" + resp.toString());
						return resp;

					}

				} catch (Exception e) {
					log.error("error:", e);
					resp.setRespCode(ResponseCode.SERVER_ERROR.getCode());
					resp.setRespDesc(ResponseCode.SERVER_ERROR.getDesc());
					log.info("return:" + resp);
					return resp;
				}
				resp.setRespCode(ResponseCode.SUCCESS.getCode());
				resp.setRespDesc(ResponseCode.SUCCESS.getDesc());
				log.info("return:" + resp.toString());
				return resp;
			}

		});

	}

	@Override
	public Future<BaseResponse> unbind(UnBindCustBrandRequest req) {
		return futurePool.apply(new Function0<BaseResponse>() {
			@Override
			public BaseResponse apply() {
				BaseResponse resp = new BaseResponse();

				if (req.getBaseReq().getSeqNo() == null) {
					resp.setSeqNo(RpcUtil.genSeqNo());
				} else {
					resp.setSeqNo(req.getBaseReq().getSeqNo());
				}
				log.info("receive:" + req);
				try {
					long customerId = req.getCustomerId();
					long brandId = req.getBrandId();
					jdbcTemplate.update("delete from cpms_cust_brand where customer_id= ? and brand_id = ? ", customerId, brandId);
				} catch (Exception e) {
					log.error("error:", e);
					resp.setRespCode(ResponseCode.SERVER_ERROR.getCode());
					resp.setRespDesc(ResponseCode.SERVER_ERROR.getDesc());
					log.info("return:" + resp);
					return resp;
				}
				resp.setRespCode(ResponseCode.SUCCESS.getCode());
				resp.setRespDesc(ResponseCode.SUCCESS.getDesc());
				log.info("return:" + resp);
				return resp;
			}

		});
	}

	@Override
	public Future<GetCustBrandResponse> getCustBrand(GetCustBrandRequest req) {
		return futurePool.apply(new Function0<GetCustBrandResponse>() {
			@Override
			public GetCustBrandResponse apply() {

				GetCustBrandResponse resp = MdpInoutUtil.getGetCustBrandResponse(RpcUtil.genSeqNo());
				BaseResponse base = resp.getBaseResp();
				if (req.getBaseReq().getSeqNo() != null) {
					base.setSeqNo(req.getBaseReq().getSeqNo());
				}
				log.info("receive:" + req.toString());
				try {
					long customerId = req.getCustomerId();
					RowMapper<TCustBrand> rowMapper = new RowMapper<TCustBrand>() {
						@Override
						public TCustBrand mapRow(ResultSet rs, int rowNum) throws SQLException {
							TCustBrand cb = new TCustBrand();
							cb.setCustomerId(customerId);
							cb.setBrandId(rs.getLong("brand_id"));
							cb.setUpdateBy(rs.getString("update_by"));
							cb.setUpdateTime(rs.getDate("update_time").getTime());
							cb.setFromSystem(rs.getString("from_system"));
							return cb;
						}
					};
					String sql = "select brand_id,update_time,update_by,from_system from cpms_cust_brand where customer_id = ? ";
					List<TCustBrand> value = jdbcTemplate.query(sql, new Object[] { customerId }, rowMapper);
					resp.setValue(value);
				} catch (Exception e) {
					log.error("error:", e);
					base.setRespCode(ResponseCode.SERVER_ERROR.getCode());
					base.setRespDesc(ResponseCode.SERVER_ERROR.getDesc());
					log.info("return:" + resp);
					return resp;
				}
				base.setRespCode(ResponseCode.SUCCESS.getCode());
				base.setRespDesc(ResponseCode.SUCCESS.getDesc());
				log.info("return:" + resp.toString());
				return resp;
			}

		});
	}
}
